﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FileUtility.EmailSender;
using System.Threading;
namespace FileMonitor.Service.Tracking.Notify
{
    public class EmailNotify:INotify
    {
        private Queue<NotifyTask> _taskQueue;
        private EmailSender _sender;

        private Thread _workThreading;
        private EventWaitHandle _waitHandle;

        private object locker = new object();

        public EmailNotify()
        {
            _taskQueue = new Queue<NotifyTask>();
            _sender = new EmailSender();
            _workThreading = new Thread(Send);
            _waitHandle = new AutoResetEvent(false);
        }
        public void StatNotify()
        {
            _workThreading.Start();
        }
        public void StopNotify()
        {
            this.Notify(null);
        }


        public void Notify(NotifyTask task) 
        {
            lock (locker)
            {
                this._taskQueue.Enqueue(task);
            }
            _waitHandle.Set();
        }

        private void Send()
        {
            while (true)
            {
                NotifyTask task = null;
                lock (locker)
                {
                    if (this._taskQueue.Count > 0)
                    {
                        task = this._taskQueue.Dequeue();
                        if (task == null)
                        {
                            return;
                        }
                    }
                }
                if (task != null)
                {
                    _sender.Send(task.RevceiveID,task.Subject,task.Content,task.AttachmentPath);
                }
                else
                    _waitHandle.WaitOne();
            }
        }
    }
}
